package org.patto.main.manage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.patto.main.api.impl.entity.SysUserLoginLog;
import org.patto.main.api.impl.mapper.SysUserLoginLogMapper;
import org.patto.common.core.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author songchuanfu
 * @ClassName LoginLogManage
 * @qq 1802284273
 * @addres 1802284273@qq.com
 * @微信: wx-suagcf
 */
@Component
@Slf4j
public class LoginLogManage {
    @Autowired
    private SysUserLoginLogMapper sysUserLoginLogMapper;

    @Async("taskExecutor")
    public void asynLoginLog(SysUserLoginLog sysUserLoginLog) {
        // 登录成功之后 需要将原来的token 令牌挤下去
        QueryWrapper<SysUserLoginLog> loginLogQueryWrapper = new QueryWrapper<>();
        loginLogQueryWrapper.eq("user_id", sysUserLoginLog.getUserId());
        loginLogQueryWrapper.eq("is_delete", 0);
        SysUserLoginLog dbUserLoginLog = sysUserLoginLogMapper.selectOne(loginLogQueryWrapper);
        String loginToken = null;
        if (dbUserLoginLog != null) {
            // 将该登录日志隐藏
            dbUserLoginLog.setIsDelete(1);
            sysUserLoginLogMapper.updateById(dbUserLoginLog);
            loginToken = dbUserLoginLog.getLoginToken();
        }
        // 新增一条登录日志 状态是为0
        sysUserLoginLog.setIsDelete(0);
        int result = sysUserLoginLogMapper.insert(sysUserLoginLog);
        log.info("<登录日志插入结果:{}>", result);

        if (result > 0 && !StringUtils.isEmpty(loginToken)) {
            log.info("<正在删除loginToken:{}>", loginToken);
            RedisUtil.delKey(loginToken);
        }
        // 调用别人接口异步发送短信
        // 唯一登录（查询db数据库）
    }
}